package sw.EngAdroid;

import java.util.ArrayList;
import java.util.List;

import netcode.client.Client;
import netcode.helper.ClientMessageListener;
import netcode.helper.NetcodeHelper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.util.DisplayMetrics;
import android.view.Window;

public class NetSixPlayerActivity extends Activity implements
		ClientMessageListener {

	private TextView currentName;
	private TextView questionText;
	private TextView question;
	private EditText answerText;
	private ArrayList<Player> players;
	private ArrayList<String> playerNames;
	private Button start;
	private Button submit;
	// private boolean notdone;
	// private int currentPlayer;
	private Game game;
	// private int numberOfPlayers;
	// private TextView myCounter;
	//private sw.EngAdroid.CountDownTimer t;
	private Button bet0;
	//private TextView guess0;
	//private TextView ratio0;
	private EditText chips0;
	// private Button bet1;
	//private TextView guess1;
	//private TextView ratio1;
	private EditText chips1;
	// private Button bet2;
	//private TextView guess2;
	//private TextView ratio2;
	private EditText chips2;
	private TextView p0chips;
	private TextView p1chips;
	private TextView p2chips;
	private TextView correctGuess;
	private Button nextRound;
	private Button endGame;
	private TextView playerNameBet;
	//private boolean isLocal = true;
	private boolean small = false;
	// private static final boolean VERBOSE = true;
	private Client client;
	private TextView hostView;
	private TextView player2View;
	private TextView player3View;
	private Button refresh;
	private Button leave;
	private boolean serverLobbyInfoReceived = false;
	private boolean gameLobbyInfoReceived = false;
	private boolean questionReceived = false;
	private boolean bettingOddsReceived = false;
	private boolean roundResultsReceived = false;
	private boolean endOfGameReceived = false;
	private Player player;
	private TextView[] guessViewArray;
	private TextView[] ratioViewArray;
	private String playerName;
	private String gameName;
	private String gameTopic;
	private Button ready;
	private int gameID;
	private TextView player4View;
	private EditText chips3;
	private TextView p3chips;
	private TextView player5View;
	private EditText chips4;
	private TextView p4chips;
	private TextView player6View;
	private EditText chips5;
	private TextView p5chips;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		Intent intent = getIntent();
		Bundle info = intent.getExtras();
		if (dm.widthPixels < 1000) {
			setContentView(R.layout.question_screen2);
			small = true;
		} else
			setContentView(R.layout.question_screen);

		// Set up all game information
		gameName = info.getString("gameName");
		playerName = info.getString("hostName");
		gameTopic = info.getString("gameTopic");
		gameID = info.getInt("gameID");
		game = new Game();
		game.setGameID(gameID);
		try {
			client = new Client(NetcodeHelper.SERVER_ADDRESS, 
					NetcodeHelper.SERVER_PORT, playerName, game);
		} catch (Exception e) {
			System.out.println(e);
		}
		client.setListener(this);
		client.start();
		client.sendConnectionRequest();
		game = client.getGame();
		

		if(info.getBoolean("isHost"))
			startLobby();
		else
			clientLobby();

	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	// Place guess in a networked game
	private void placeGuess() {
		if (small)
			setContentView(R.layout.question_screen2);
		else
			setContentView(R.layout.question_screen);

		currentName = (TextView) findViewById(R.id.playerName);
		questionText = (TextView) findViewById(R.id.questionText);
		answerText = (EditText) findViewById(R.id.answerTextBox);
		submit = (Button) findViewById(R.id.submitAnswerButton);
		
		Question question = game.getQuestion();
		currentName.setText(game.getPlayers().get(0).getPlayer_name());
		questionText.setText(question.getText());
		submit.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				int numGuess = Integer
						.parseInt(answerText.getText().toString());
				bettingOddsReceived = false;
				client.sendAnswer(game.getGameID(), numGuess);
				do {
					sleepyTime();
				} while (!bettingOddsReceived);
				placeBets();
			}
		});

	}

	// display client lobby
	private void clientLobby() {
		if (small)
			setContentView(R.layout.lobby_guest_screen6_small);
		else
			setContentView(R.layout.lobby_guest_screen6);
		leave = (Button) findViewById(R.id.button4);
		hostView = (TextView) findViewById(R.id.textView2);
		player2View = (TextView) findViewById(R.id.player2);
		player3View = (TextView) findViewById(R.id.player3);
		player4View = (TextView) findViewById(R.id.player4);
		player5View = (TextView) findViewById(R.id.player5);
		player6View = (TextView) findViewById(R.id.player6);
		ready = (Button) findViewById(R.id.ready);
		
		players = game.getPlayers();
		playerNames = new ArrayList<String>();

		for (int i = 0; i < players.size(); i++) {
			playerNames.add(players.get(i).getPlayer_name());
			if (players.get(i).getPlayer_name().equals(playerName)) {
				player = players.get(i);
			}
		}
		
		ready.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				do{
					sleepyTime();
				} while(!questionReceived);
				questionReceived = false;
				placeBets();
			}
		});
		
		leave.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				client.sendLeaveGameRequest(game.getGameID());
				finish();
			}
		});
		
		
	}

	// Bring up the lobby waiting screen for networked games
	private void startLobby() {
		// show the lobby screen
		if (small)
			setContentView(R.layout.lobby_host_screen6_small);
		else
			setContentView(R.layout.lobby_host_screen6);
		start = (Button) findViewById(R.id.button4);
		hostView = (TextView) findViewById(R.id.textView2);
		player2View = (TextView) findViewById(R.id.textView6);
		player3View = (TextView) findViewById(R.id.textView11);
		player4View = (TextView) findViewById(R.id.textView9);
		player5View = (TextView) findViewById(R.id.textView3);
		player6View = (TextView) findViewById(R.id.textView4);
		refresh = (Button) findViewById(R.id.refreshButton2);
		leave = (Button) findViewById(R.id.button1);

		// Set up Client
		try {
			String[] topics = new String[] { gameTopic };
			// TODO: Don't leave this at 2 rounds
			client.sendCreateGameRequest(gameName, 2, topics);
		} catch (Exception e) {
			System.err.println(e);
		}

		// Code for start button
		start.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				if (game.getGameID() != 0 && game.getPlayers().size() == 6) {
					DisplayMetrics dm = new DisplayMetrics();
					getWindowManager().getDefaultDisplay().getMetrics(dm);

					if (dm.widthPixels < 1000) {
						setContentView(R.layout.question_screen2);
						small = true;
					} else
						setContentView(R.layout.question_screen);

					players = game.getPlayers();
					playerNames = new ArrayList<String>();

					for (int i = 0; i < players.size(); i++) {
						playerNames.add(players.get(i).getPlayer_name());
						if (players.get(i).getPlayer_name().equals(playerName)) {
							player = players.get(i);
						}
					}

					do {
						client.sendStartGameRequest(game.getGameID());
						sleepyTime();
					} while (!questionReceived);
					questionReceived = false;
					placeGuess();
				}
			}
		});

		refresh.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				player5View.setText("None               ");
				player5View.setText("None               ");
				player4View.setText("None               ");
				player3View.setText("None               ");
				player2View.setText("None               ");
				switch (game.getPlayers().size()) {
				case 6:
					player5View.setText(game.getPlayers().get(5)
							.getPlayer_name());
				case 5:
					player5View.setText(game.getPlayers().get(4)
							.getPlayer_name());
				case 4:
					player4View.setText(game.getPlayers().get(3)
							.getPlayer_name());
				case 3:
					player3View.setText(game.getPlayers().get(2)
							.getPlayer_name());
				case 2:
					player2View.setText(game.getPlayers().get(1)
							.getPlayer_name());
				case 1:
					hostView.setText(game.getPlayers().get(0).getPlayer_name());
				}
			}
		});

		leave.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				client.sendLeaveGameRequest(game.getGameID());
				finish();
			}
		});
	}

	private void placeBets() {
		if (small)
			setContentView(R.layout.playerboard6small);
		else
			setContentView(R.layout.playerboard6);

		// Set up all the screen elements

		bet0 = (Button) findViewById(R.id.confirm01);
		question = (TextView) findViewById(R.id.questionTextView1);
		// guess0 = (TextView) findViewById(R.id.guess01);
		// ratio0 = (TextView) findViewById(R.id.ratio01);
		chips0 = (EditText) findViewById(R.id.chips01);
		// bet1 = (Button)findViewById(R.id.confirm02);
		// guess1 = (TextView) findViewById(R.id.guess02);
		// ratio1 = (TextView) findViewById(R.id.ratio02);
		chips1 = (EditText) findViewById(R.id.chips02);
		// bet2 = (Button)findViewById(R.id.confirm03);
		// guess2 = (TextView) findViewById(R.id.guess03);
		// ratio2 = (TextView) findViewById(R.id.ratio03);
		chips2 = (EditText) findViewById(R.id.chips03);
		chips3 = (EditText) findViewById(R.id.chips04);
		chips4 = (EditText) findViewById(R.id.chips05);
		chips5 = (EditText) findViewById(R.id.chips06);
		playerNameBet = (TextView) findViewById(R.id.gameNameView);
		playerNameBet.setText("Player name: " + playerName);
		guessViewArray = new TextView[6];
		ratioViewArray = new TextView[6];
		guessViewArray[0] = (TextView) findViewById(R.id.guess01);
		guessViewArray[1] = (TextView) findViewById(R.id.guess02);
		guessViewArray[2] = (TextView) findViewById(R.id.guess03);
		guessViewArray[3] = (TextView) findViewById(R.id.guess04);
		guessViewArray[4] = (TextView) findViewById(R.id.guess05);
		guessViewArray[5] = (TextView) findViewById(R.id.guess06);
		ratioViewArray[0] = (TextView) findViewById(R.id.ratio01);
		ratioViewArray[1] = (TextView) findViewById(R.id.ratio02);
		ratioViewArray[2] = (TextView) findViewById(R.id.ratio03);
		ratioViewArray[3] = (TextView) findViewById(R.id.ratio04);
		ratioViewArray[4] = (TextView) findViewById(R.id.ratio05);
		ratioViewArray[5] = (TextView) findViewById(R.id.ratio06);

		List<Guess> guesses = game.getGuesses();
		for (int i = 0; i < guesses.size(); i++) {
			guessViewArray[i].setText("Guess: " + guesses.get(i).getGuess());
			ratioViewArray[i].setText("Ratio: " + guesses.get(i).getOdds());
		}
		// guess0.setText("Guess: " + guesses.get(0).getGuess());
		// guess1.setText("Guess: " + guesses.get(1).getGuess());
		// guess2.setText("Guess: " + guesses.get(2).getGuess());
		// ratio0.setText("Ratio: " + guesses.get(0).getOdds());
		// ratio1.setText("Ratio: " + guesses.get(1).getOdds());
		// ratio2.setText("Ratio: " + guesses.get(2).getOdds());

		bet0.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				int permChips = player.getPermanent_chips();
				int gameChips = player.getGame_chips();

				ArrayList<Bet> bets = new ArrayList<Bet>();
				String one = chips0.getText().toString();
				int permChipsBet = 0;
				int gameChipsBet = 0;
				if (!(one.equals(""))) {
					int chipsBet = Integer.parseInt(one);

					if (permChips > 0 && permChips < chipsBet) {
						permChipsBet = permChips;
						chipsBet -= permChips;
						permChips = 0;

					} else if (permChips > 0 && permChips > chipsBet) {
						permChipsBet = chipsBet;
						permChips -= chipsBet;
					}
					if (gameChips > 0 && gameChips < chipsBet) {
						gameChipsBet = gameChips;
						chipsBet -= gameChips;
						gameChips = 0;
					} else if (gameChips > 0 && gameChips > chipsBet) {
						gameChipsBet = chipsBet;
						gameChips -= chipsBet;
					}
					bets.add(new Bet(playerName, 0, permChipsBet, gameChipsBet));
				}
				String two = chips1.getText().toString();
				if (!(two.equals(""))) {
					int chipsBet = Integer.parseInt(two);

					if (permChips > 0 && permChips < chipsBet) {
						permChipsBet = permChips;
						chipsBet -= permChips;
						permChips = 0;

					} else if (permChips > 0 && permChips > chipsBet) {
						permChipsBet = chipsBet;
						permChips -= chipsBet;
					}
					if (gameChips > 0 && gameChips < chipsBet) {
						gameChipsBet = gameChips;
						chipsBet -= gameChips;
						gameChips = 0;
					} else if (gameChips > 0 && gameChips > chipsBet) {
						gameChipsBet = chipsBet;
						gameChips -= chipsBet;
					}
					bets.add(new Bet(playerName, 1, permChipsBet, gameChipsBet));
				}
				String three = chips2.getText().toString();
				if (!(three.equals(""))) {
					int chipsBet = Integer.parseInt(three);

					if (permChips > 0 && permChips < chipsBet) {
						permChipsBet = permChips;
						chipsBet -= permChips;
						permChips = 0;

					} else if (permChips > 0 && permChips > chipsBet) {
						permChipsBet = chipsBet;
						permChips -= chipsBet;
					}
					if (gameChips > 0 && gameChips < chipsBet) {
						gameChipsBet = gameChips;
						chipsBet -= gameChips;
						gameChips = 0;
					} else if (gameChips > 0 && gameChips > chipsBet) {
						gameChipsBet = chipsBet;
						gameChips -= chipsBet;
					}
					bets.add(new Bet(playerName, 2, permChipsBet, gameChipsBet));
				}
				String four = chips3.getText().toString();
				if (!(four.equals(""))) {
					int chipsBet = Integer.parseInt(one);

					if (permChips > 0 && permChips < chipsBet) {
						permChipsBet = permChips;
						chipsBet -= permChips;
						permChips = 0;

					} else if (permChips > 0 && permChips > chipsBet) {
						permChipsBet = chipsBet;
						permChips -= chipsBet;
					}
					if (gameChips > 0 && gameChips < chipsBet) {
						gameChipsBet = gameChips;
						chipsBet -= gameChips;
						gameChips = 0;
					} else if (gameChips > 0 && gameChips > chipsBet) {
						gameChipsBet = chipsBet;
						gameChips -= chipsBet;
					}
					bets.add(new Bet(playerName, 3, permChipsBet, gameChipsBet));
				}
				String five = chips4.getText().toString();
				if (!(two.equals(""))) {
					int chipsBet = Integer.parseInt(two);

					if (permChips > 0 && permChips < chipsBet) {
						permChipsBet = permChips;
						chipsBet -= permChips;
						permChips = 0;

					} else if (permChips > 0 && permChips > chipsBet) {
						permChipsBet = chipsBet;
						permChips -= chipsBet;
					}
					if (gameChips > 0 && gameChips < chipsBet) {
						gameChipsBet = gameChips;
						chipsBet -= gameChips;
						gameChips = 0;
					} else if (gameChips > 0 && gameChips > chipsBet) {
						gameChipsBet = chipsBet;
						gameChips -= chipsBet;
					}
					bets.add(new Bet(playerName, 4, permChipsBet, gameChipsBet));
				}
				String six = chips5.getText().toString();
				if (!(two.equals(""))) {
					int chipsBet = Integer.parseInt(two);

					if (permChips > 0 && permChips < chipsBet) {
						permChipsBet = permChips;
						chipsBet -= permChips;
						permChips = 0;

					} else if (permChips > 0 && permChips > chipsBet) {
						permChipsBet = chipsBet;
						permChips -= chipsBet;
					}
					if (gameChips > 0 && gameChips < chipsBet) {
						gameChipsBet = gameChips;
						chipsBet -= gameChips;
						gameChips = 0;
					} else if (gameChips > 0 && gameChips > chipsBet) {
						gameChipsBet = chipsBet;
						gameChips -= chipsBet;
					}
					bets.add(new Bet(playerName, 5, permChipsBet, gameChipsBet));
				}
				client.sendSubmitBets(bets, game.getGameID());
				do {
					sleepyTime();
				} while (!roundResultsReceived);
				roundResultsReceived = false;

				winnings();

			}
		});
	}

	private void winnings() {
		if (small)
			setContentView(R.layout.winnings6small);
		else
			setContentView(R.layout.winnings6);

		// game.winnings();
		p0chips = (TextView) findViewById(R.id.player0);
		p1chips = (TextView) findViewById(R.id.player1);
		p2chips = (TextView) findViewById(R.id.player2);
		p3chips = (TextView) findViewById(R.id.player3);
		p4chips = (TextView) findViewById(R.id.player4);
		p5chips = (TextView) findViewById(R.id.player5);
		correctGuess = (TextView) findViewById(R.id.correctGuess);
		correctGuess.setText("Correct answer: "
				+ game.getQuestion().getAnswer());
		p0chips.setText(game.getPlayers().get(0).getPlayer_name()
				+ "'s chips: " + game.getPlayers().get(0).getChips());
		p1chips.setText(game.getPlayers().get(1).getPlayer_name()
				+ "'s chips: " + game.getPlayers().get(1).getChips());
		p2chips.setText(game.getPlayers().get(2).getPlayer_name()
				+ "'s chips: " + game.getPlayers().get(2).getChips());
		p3chips.setText(game.getPlayers().get(3).getPlayer_name()
				+ "'s chips: " + game.getPlayers().get(3).getChips());
		p4chips.setText(game.getPlayers().get(4).getPlayer_name()
				+ "'s chips: " + game.getPlayers().get(4).getChips());
		p4chips.setText(game.getPlayers().get(5).getPlayer_name()
				+ "'s chips: " + game.getPlayers().get(5).getChips());
		nextRound = (Button) findViewById(R.id.again);
		endGame = (Button) findViewById(R.id.endGame);
		nextRound.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				do {
					sleepyTime();
				} while (!questionReceived && !endOfGameReceived);
				if (endOfGameReceived) {
					client.sendLeaveGameRequest(game.getGameID());
					client.sendDisconnect();
					finish();
				} else {
					questionReceived = false;
					placeGuess();
				}
			}
		});

		endGame.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				client.sendLeaveGameRequest(game.getGameID());
				client.sendDisconnect();
				finish();
			}
		});

	}

	public void onMessageReceived(byte packetCode) {
		System.out.println("onMessageReceived() entered with code: "
				+ packetCode);
		switch (packetCode) {
		case NetcodeHelper.SERVER_LOBBY_INFO_RESPONSE:
			serverLobbyInfoReceived = true;
			break;
		case NetcodeHelper.GAME_LOBBY_INFO:
			gameLobbyInfoReceived = true;
			break;
		case NetcodeHelper.QUESTION:
			questionReceived = true;
			break;
		case NetcodeHelper.BETTING_ODDS:
			bettingOddsReceived = true;
			break;
		case NetcodeHelper.ROUND_RESULTS:
			roundResultsReceived = true;
			break;
		case NetcodeHelper.GAME_RESULTS:
			endOfGameReceived = true;
			break;
		}

	}

	public void sleepyTime() {
		try {
			Thread.sleep(NetcodeHelper.MILLISECONDS_BETWEEN_SENDING_MESSAGE);
		} catch (Exception e) {
			System.err.println(e);
		}
	}
}
